/*
* @Author: Administrator
* @Date:   2018-01-10 11:06:52
* @Last Modified by:   Administrator
* @Last Modified time: 2018-01-27 15:03:59
*/
const path = require('path')
const axios = require('axios')
const NativeModule = require('module');
const vm = require('vm');
const httpProxy = require('http-proxy-middleware')
const webpack = require('webpack')
const MemroyFs = require('memory-fs');

const serverConfig = require('../../webpack.server.config.js')

const compiled = webpack(serverConfig);
const mfs = new MemroyFs()

const serverRender = require('./server_render.js')

const getTemplate = () => {
  return new Promise((resolve, reject) => {
    axios.get('http://localhost:8084/dist/server_template.ejs')
    .then(res => resolve(res.data))
    .catch(reject)
  })
}

const getModuleFromString = (bundle,filename) => {
  const m = { exports:{} }
  const wrapper = NativeModule.wrap(bundle);
  const script = new vm.Script(wrapper,{
    filename: filename,
    displayErrors: true,
  });
  const result = script.runInThisContext();
  result.call(m.exports, m.exports, require, m);
  return m;
}


compiled.outputFileSystem = mfs
let bundle
compiled.watch({},function(error,stats) {
  if(error) {
    throw error
  }
  var stats = stats.toJson()
  stats.errors.forEach(err => console.log(err))
  stats.warnings.forEach(warn => console.log(warn))
  const bundlePath = path.join(serverConfig.output.path,serverConfig.output.filename)
  bundle = mfs.readFileSync(bundlePath, 'utf-8')
})

const serverDev = (app) => {
  app.use('/dist',httpProxy({
    target: 'http://localhost:8084/'
  }))
  app.get('*', function(req, res, next) {
    if(!bundle) {
      res.send('等待编译')
      res.end()
      return
    }
    getTemplate().then(template => {
      const bundleModule = getModuleFromString(bundle,'server/server.js').exports;
      serverRender(bundleModule, template, req, res).catch(next)
    }).catch(next)
  })
}

module.exports = serverDev
